module.exports = (main.toString()).replace(/function main\(\) \{/g, "{");

function main() {
    importClass(Packages.androidx.recyclerview.widget.ItemTouchHelper);
    importClass(android.view.View);
    importClass(android.os.Build);
    importClass(android.graphics.Typeface);

    var themeJs = require("./theme.js");
    var sortJs = require("./sort.js");
    var coloringJs = require("./coloring.js");
    var rewriteWordJs = require("./rewriteWord.js");
    var networkSourceJs = require("./networkSource.js");
    var addWordJs = require("./addWord.js");
    var playMusicJs = require("./playMusic.js");
    
    var parent = {};
    parent.theme = themeJs;

    var resources = activity.getResources();
    var resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
    var bar_height = resources.getDimensionPixelSize(resourceId);
    
    dialogs.setDefaultDialogType("app");
    ui.statusBarColor(themeJs.bar);

    ui.layout(
        <vertical>
            <appbar>
                <toolbar id="toolbar" title="工作区" bg="{{themeJs.bar}}">
                    <text id="count" text="0"  textColor="#bbbbbb" textSize="12"/>
                    <img id="sort" layout_gravity="right" src="@drawable/ic_sort_black_48dp" w="20" h="*" scaleType="fitCenter" tint="#ffffff" bg="?selectableItemBackgroundBorderless"/>
                </toolbar>
            </appbar>
            <frame layout_weight="1">
                <list id="wordList" h="*" bg="{{themeJs.parent_layout}}">
                    <card w="*" h="auto" id="card" margin="10 5" cardCornerRadius="2dp" cardElevation="1dp" cardBackgroundColor="{{this.parent.theme.layout}}" foreground="?selectableItemBackground">
                        <frame>
                            <vertical gravity="center_vertical">
                                <vertical padding="10 8" h="*" w="*">
                                    <horizontal visibility="{{this.parent.hideWord?'invisible':'visible'}}" gravity="bottom">
                                        <text id="title" text="{{this.word}}" textColor="{{this.parent.theme.text}}" textSize="16" maxLines="1" textStyle="bold"/>
                                        <text id="count" text="{{'('+this.count+')'}}" layout_gravity="top" textColor="{{this.parent.theme.text2}}" textSize="8" visibility="{{this.count == null || this.count == 0 ?'gone':'visible'}}"/>
                                    </horizontal>
                                    <horizontal visibility="{{this.parent.hideWord?'invisible':'visible'}}">
                                        <horizontal visibility="{{this.parent.phShow == 0 || this.parent.phShow == 2 ? (this.en==null||this.en==''?(this.parent.hideVudioIcon?'gone':'visible'):'visible'):'gone'}}">
                                            <text id="en" text="{{'英'+(this.en==null||this.en==''?'':'['+this.en+']')}}" textColor="{{this.parent.theme.text3}}" textSize="12" maxLines="1" />
                                            <img id="enVudio" src="@drawable/ic_volume_up_black_48dp" layout_gravity="bottom" marginLeft="5" w="16" h="16"/>
                                        </horizontal>
                                        <horizontal visibility="{{this.parent.phShow == 1 || this.parent.phShow == 2 ? (this.am==null||this.am==''?(this.parent.hideVudioIcon?'gone':'visible'):'visible'):'gone'}}">
                                            <text id="am" text="{{'美'+(this.am==null||this.am==''?'':'['+this.am+']')}}" marginLeft="10" textColor="{{this.parent.theme.text3}}" textSize="12" maxLines="1" />
                                            <img id="amVudio" src="@drawable/ic_volume_up_black_48dp" layout_gravity="bottom" marginLeft="5" w="16" h="16"/>
                                        </horizontal>
                                    </horizontal>
                                    <text id="meaning" text="{{this.parent.hideMean ? '' : this.meaning}}" singleLine="{{this.parent.singleLine}}" visibility="{{this.parent.hideMean?'invisible':'visible'}}" ellipsize="end" textColor="{{this.parent.theme.text2}}" textSize="12"/>
                                    <text id="updateFlag" text="{{this.updateFlag}}" visibility="gone"/>
                                </vertical>
                                <View bg="{{this.color}}" h="2" w="*" />
                            </vertical>
                            <img id="bookmark" src="@drawable/ic_bookmark_black_48dp" visibility="{{this.hasMark == null || this.parent.hideWord || this.parent.hideMean ? 'gone' : 'visible'}}" tint="{{this.color}}" layout_gravity="right|top" w="12" h="12" marginRight="8"/>
                        </frame>
                    </card>
                </list>
                <text id="prompt" gravity="center" h="*" textColor="{{themeJs.text2}}"/>
            </frame>
            <toolbar layout_gravity="bottom" padding="8 0" bg="{{themeJs.layout}}">
                <horizontal w="*">
                    <vertical layout_weight="1" w="*" gravity="center">
                        <img id="play" src="@drawable/ic_play_arrow_black_48dp" w="24" h="50" scaleType="fitCenter" tint="#868686" bg="?selectableItemBackgroundBorderless"/>
                    </vertical>
                    <vertical layout_weight="1" w="*" gravity="center">
                        <img id="add" src="@drawable/ic_add_circle_outline_black_48dp" w="24" h="50" scaleType="fitCenter" tint="#868686" bg="?selectableItemBackgroundBorderless"/>
                    </vertical>
                    <vertical layout_weight="1" w="*" gravity="center">
                        <img id="slideshow" src="@drawable/ic_slideshow_black_48dp" w="24" h="50" scaleType="fitCenter" tint="#868686" bg="?selectableItemBackgroundBorderless"/>
                    </vertical>
                </horizontal>
            </toolbar>
        </vertical>
    );

    var storage;
    var wordList;
    var isFromNet;
    var count;
    var currentList = {};
    var workTitle;

    function enter(title, sdcard) {
        ui.toolbar.title = title;
        workTitle = title;
        //获取单词储存
        storage = storages.create("wordbook45qq_wordList_" + sdcard);
        //获取单词列表
        wordList = storage.get("list", []);
        currentList.wordList = wordList;
        //获取单词个数
        updateCount();

        //将parent重新赋给wordlist，让字符串变为对象
        for (let i in wordList) {
            wordList[i].parent = parent;
        }

        ui.post(() => {
            ui.wordList.setDataSource(currentList.wordList);
        });
    }

    //获取设置
    var settingStorage = storages.create("wordbook45qq_setting");
    //是否隐藏单词
    parent.hideWord = settingStorage.get("hideWord", false);
    //是否单行显示
    parent.singleLine = settingStorage.get("singleLine", false);
    //是否隐藏释义
    parent.hideMean = settingStorage.get("hideMean", false);
    //音标为空时隐藏播放按钮
    parent.hideVudioIcon = settingStorage.get("hideVudioIcon", true);
    //音标显示
    parent.phShow = settingStorage.get("phShow", 2);
    //播放偏好
    parent.phType = settingStorage.get("phType", "en");
    //只显示书签
    parent.onlyBookmark = false;

    if (parent.phShow != 2)
        if (parent.phShow == 0)
            parent.phType = "en";
        else parent.phType = "an";
    //设置金山翻译源
    parent.netFrom = settingStorage.get("netFrom", 0);

    //保存单词跟设置
    ui.emitter.on("pause", () => {
        playData.isPlay = false;

        settingStorage.put("singleLine", parent.singleLine);
        settingStorage.put("hideWord", parent.hideWord);
        settingStorage.put("hideMean", parent.hideMean);
        settingStorage.put("hideVudioIcon", parent.hideVudioIcon);
        settingStorage.put("phType", parent.phType);
        settingStorage.put("netFrom", parent.netFrom);
        settingStorage.put("phShow", parent.phShow);

        for (let i in wordList)
            delete wordList[i]["parent"];
        storage.put("list", wordList);
        for (let i in wordList) {
            wordList[i].parent = parent;
        }
    });

    var menuBuilder;
    //创造右上角菜单
    ui.emitter.on("create_options_menu", menu => {
        menuBuilder = menu;
        menu.add(parent.hideWord ? "显示单词" : "隐藏单词");
        menu.add(parent.hideMean ? "显示释义" : "隐藏释义");
        menu.add(parent.singleLine ? "多行显示" : "单行显示");
        menu.add(parent.onlyBookmark ? "显示全部" : "仅显示书签");
    });

    //监听选项菜单点击
    ui.emitter.on("options_item_selected", (e, item) => {
        switch (item.title) {
            case "隐藏单词":
                if (parent.hideMean) {
                    parent.hideMean = false;
                    ui.post(() => {
                        menuBuilder.getItem(1).title = "隐藏释义";
                    }, 500);
                }
            case "显示单词":
                ui.post(() => {
                    parent.hideWord = !parent.hideWord;
                    ui.run(() => {
                        ui.wordList.getAdapter().notifyDataSetChanged();
                        item.title = parent.hideWord ? "显示单词" : "隐藏单词";
                    });
                }, 500);
                break;
            case "隐藏释义":
                if (parent.hideWord) {
                    parent.hideWord = false;
                    ui.post(() => {
                        menuBuilder.getItem(0).title = "隐藏单词";
                    }, 500);
                }
            case "显示释义":
                ui.post(() => {
                    parent.hideMean = !parent.hideMean;
                    ui.run(() => {
                        ui.wordList.getAdapter().notifyDataSetChanged();
                        item.title = parent.hideMean ? "显示释义" : "隐藏释义";
                    });
                }, 500);
                break;
            case "单行显示":
            case "多行显示":
                ui.post(() => {
                    parent.singleLine = !parent.singleLine;
                    ui.run(() => {
                        ui.wordList.getAdapter().notifyDataSetChanged();
                        item.title = parent.singleLine ? "多行显示" : "单行显示";
                    });
                }, 500);
                break;
            case "格式化":
                confirm("确定要格式化工作区吗？", "该操作将会清空这个工作区的所有单词QAQ")
                    .then(ok => {
                        if (ok) {
                            wordList.splice(0, wordList.length);
                            currentList.wordList.splice(0, currentList.wordList.length);
                            updateCount();
                            toast("已格式化工作区！");
                        }
                    });
                break;
            case "仅显示书签":
                ui.post(() => {
                    let bookmarkList = [],
                        word, neww;
                    for (let i in wordList) {
                        word = wordList[i];
                        if (word.hasMark) {
                            neww = JSON.parse(JSON.stringify(word));
                            neww.id = i;
                            bookmarkList.push(word);
                        }
                    }
                    currentList.wordList = bookmarkList;
                    parent.onlyBookmark = true;
                    ui.run(() => {
                        updateCount();
                        updateBookmark();
                        ui.wordList.setDataSource(bookmarkList);
                        item.title = "显示全部";
                    });
                }, 500);
                break;
            case "显示全部":
                ui.post(() => {
                    currentList.wordList = wordList;
                    parent.onlyBookmark = false;
                    ui.run(() => {
                        updateCount();
                        updateBookmark();
                        ui.wordList.setDataSource(wordList);
                        item.title = "仅显示书签";
                    });
                }, 500);
                break;
        }
        e.consumed = true;
    });

    ui.sort.on("click", () => {
        sortJs.show(currentList.wordList);
    });

    new ItemTouchHelper(new ItemTouchHelper.Callback({
        isItemViewSwipeEnabled: function() {
            return true;
        },
        getMovementFlags: function(recyclerView, viewHolder) {
            return this.makeMovementFlags(0, ItemTouchHelper.LEFT);
        },
        onMove: function(recyclerView, srcHolder, targetHolder) {
            return true;
        },
        onSwiped: function(viewHolder, direction) {
            removeItem(viewHolder.getAdapterPosition(), true);
        },
    })).attachToRecyclerView(ui.wordList);

    activity.setSupportActionBar(ui.toolbar);

    ui.slideshow.on("click", (view) => {
        let strlist = "[";
        let uselist = ui.wordList.getDataSource();
        for (let i in uselist) {
            if (strlist != "[")
                strlist += ",";
            strlist += JSON.stringify(uselist[i]);
        }
        strlist += "]";
        engines.execScript("slideshow_ui", "'ui';" + require('./slideshow.js') + "enter(" + strlist + ");");
    });

    //单词放映配置
    var playData = {
        isPlay: false,
        index: 0,
    };

    //设置放映按钮监听
    var isInPlay = false;
    ui.play.on("click", (view) => {
        playData.isPlay = !playData.isPlay;
        if (playData.isPlay)
            view.setSource("@drawable/ic_pause_black_48dp");
        else view.setSource("@drawable/ic_play_arrow_black_48dp");
        if (play_thread == null || !play_thread.isAlive())
            playShow();
    });

    var play_thread;
    //递归播放单词
    function playShow() {
        if (!playData.isPlay) {
            ui.play.setSource("@drawable/ic_play_arrow_black_48dp");
            return;
        }

        var view, b, word, item, ph;
        view = ui.wordList.getLayoutManager().findViewByPosition(playData.index);
        b = parent.phType == "en" ? true : false;
        word = currentList.wordList[playData.index];
        if (word == null) {
            toast("先去添加一个吧～")
            playData.index = 0;
            playData.isPlay = false;
            ui.play.setSource("@drawable/ic_play_arrow_black_48dp");
            return;
        }
        ph = b ? word.en_mp3 : word.am_mp3;

        playData.index++;
        if (playData.index == currentList.wordList.length) {
            playData.index = 0;
            playData.isPlay = false;
            toast("已播放完列表");
        }
        if ((b && (word.en == null || word.en == "")) || (!b && (word.am == null || word.am == ""))) {
            playShow();
            return;
        }
        if (view != null) {
            item = b ? view.enVudio : view.amVudio;
        }
        play_thread = threads.start(function() {
            if (playMusicJs.playMusicFromWord(item, word.word, parent.phType))
                sleep(500);
            playShow();
        });
    }

    //设置是否隐藏图标回调
    parent.isHideVudioIcon = function(ph) {
        return (ph == null || ph == "") && parent.hideVudioIcon ? '0' : '16';
    }

    //监听item刷新，并为文本着色
    ui.wordList.addOnChildAttachStateChangeListener({
        onChildViewAttachedToWindow: function(view) {
            let list = currentList.wordList[ui.wordList.getLayoutManager().getPosition(view)];
            if (list != null && !parent.hideMean && (!list.bold && list.bold != null)) {
                view.title.setTypeface(Typeface.SERIF);
            }
            let text = view.meaning.text();
            if (view.updateFlag.text() == "true" && coloringJs.canColor(text))
                ui.run(() => {
                    view.meaning.setText(coloringJs.getColoringStr(text));
                    view.updateFlag.setText("false");
                });
        },
        onChildViewDetachedFromWindow: function(view) {
            let list = currentList.wordList[ui.wordList.getLayoutManager().getPosition(view)];
            if (list != null && !parent.hideMean && (!list.bold && list.bold != null))
                view.title.setTypeface(Typeface.DEFAULT_BOLD);
        }
    });

    let showView = ui.inflate(
    <frame>
        <img id="bookmark" src="@drawable/ic_bookmark_black_48dp" layout_gravity="right|top" w="15" h="15" marginRight="8" visibility="gone"/>
        <vertical padding="16 20">
            <text id="word" textSize="20" textColor="{{themeJs.text}}"/>
            <text id="mean" textColor="{{themeJs.text}}" marginTop="10"/>
        </vertical>
    </frame>, null, false);

    // 显示对话框
    var showDialogs = dialogs.build({
        customView: showView,
        titleColor: themeJs.text,
        positive: "编辑",
        neutral: "删除",
        negative: "取消",
        wrapInScrollView: false,
        autoDismiss: true
    }).on("positive", ()=> {
        let item = lond_item.item;
        let id = lond_item.id;
        
        rewriteWordJs.show(item.word, item.bold, item.meaning, function(word, isBold, meaning) {
            item.word = word;
            item.bold = isBold;
            item.meaning = meaning;
            
            threads.start(function() {
                let tran = networkSourceJs.getMeaning(word);
                item.en = tran.en;
                item.am = tran.am;
                ui.run(() => {
                    updateIndex(id);
                    itemView.title.setTypeface(bold ? Typeface.DEFAULT_BOLD : Typeface.DEFAULT);
                });
            });
        }, function(index) {
            if (item.count == null)
                item.count = 0;
           
            if (index == 0)
                item.count++;
            else if (index == 1) {
                if (item.count - 1 >= 0) item.count--;
            } else if (index == 2) 
                item.count = 0;
            
            updateIndex(id);
            events.broadcast.emit("update_count_sort", {0:currentList.wordList, 1:id});
        });
    }).on("neutral", ()=> {
        removeItem(lond_item.id);
    });
    
    showView.getParent().getParent().attr("bg", themeJs.layout);
    
    var lond_item = {};
    
    //长按重新编辑单词
    ui.wordList.on("item_long_click", function(e, item, id, itemView, listView) {
        showView.word.setText(item.word);
        showView.word.setTypeface(item.bold == null || item.bold ? Typeface.DEFAULT_BOLD : Typeface.SERIF);
        showView.mean.setText(coloringJs.getColoringStr(item.meaning));
        if (item.hasMark) {
            showView.bookmark.attr("tint", item.color);
            showView.bookmark.setVisibility(View.VISIBLE);
        } else showView.bookmark.setVisibility(View.GONE);
        
        lond_item.item = item;
        lond_item.id = id;
        
        showDialogs.show();
        
        e.consumed = true;
    });

    var currentItem = {};
    var old_time = 0;
    var clickThread;
    ui.wordList.on("item_bind", function(itemView, itemHolder) {
        var clickThreak;
        //绑定item点击
        itemView.card.on("click", () => {
            let new_time = java.lang.System.currentTimeMillis();
            if (new_time - old_time <= 300) {
                old_time = 0;
                if (clickThread != null && clickThread.isAlive)
                    clickThread.interrupt();
                if (itemHolder.item.hasMark)
                    itemHolder.item.hasMark = null;
                else itemHolder.item.hasMark = true;
                updateIndex(ui.wordList.getLayoutManager().getPosition(itemView));
            } else {
                old_time = new_time;
                clickThread = threads.start(function() {
                    sleep(300);
                    if (playData.isPlay)
                        playData.index = itemHolder.getPosition();
                });
            }
        });
        //单词播放监听英式
        itemView.enVudio.on("click", function(view) {
            parent.phType = "en";
            playData.isShow = false;
            threads.start(function() {
                playMusicJs.playMusicFromWord(view, itemHolder.item.word, "en");
            });
        });
        //美式读音监听
        itemView.amVudio.on("click", function(view) {
            parent.phType = "am";
            playData.isShow = false;
            threads.start(function() {
                playMusicJs.playMusicFromWord(view, itemHolder.item.word, "am");
            });
        });
    });

    function updateCount() {
        ui.count.setText("总计 " + currentList.wordList.length + " 词");
        if (currentList.wordList.length == 0) {
            if (parent.onlyBookmark)
                ui.prompt.setText("您还没有书签呢(๑❛ᴗ❛๑)\n双击单词以添加书签");
            else ui.prompt.setText(coloringJs.getStrFromHtml("这里什么也没有ㄟ(▔，▔)ㄏ<br>点击下方的“ <b><font color='#29B6F6'>⊕</font></b> ”添加单词"));
            ui.prompt.setVisibility(View.VISIBLE);
        } else ui.prompt.setVisibility(View.GONE);
    }
    
    function updateBookmark() {
        if (parent.onlyBookmark)
                ui.toolbar.title = workTitle + "[书签]";
        else ui.toolbar.title = workTitle;
    }

    //加入单词监听
    ui.add.on("click", () => {
        addWordJs.show(wordList, function(item, i) {
            item.parent = parent;
            updateCount();
            ui.post(() => {
                ui.wordList.scrollToPosition(i);
            }, 500);
        });
    });
    
    function updateIndex(index) {
        ui.wordList.getAdapter().notifyItemChanged(index);
    }
    
    function removeItem(index, updateItem) {
        confirm("确定要删除" + currentList.wordList[index].word + "吗？")
                .then(ok => {
                    if (updateItem) updateIndex(index);
                    if (ok) {
                        ui.post(() => {
                            if (currentList.wordList.id == null)
                                wordList.splice(index, 1);
                            else {
                                wordList.splice(currentList.wordList[index].id, 1);
                                currentList.wordList.splice(index, 1);
                            }
                            updateCount();
                        });
                    }
                });
    }

    events.broadcast.on("slideshow_hasMark_return", function(json) {
        wordList[json.id].hasMark = json.hasMark;
        updateIndex(json.id);
    });
    
    events.broadcast.on("update_wordlist_index", function(index) {
        updateIndex(index);
    });

}